import { syncSetTimeout, sendMessage, getMessage, dispatch } from "../../global/tools.js";

export default class Call {
    static count = 0;
    constructor(webController) {
        Call.count++;
        if (Call.count >= 2) {
            alert("collectionPlugin: \nError: Call.count >= 2，即将刷新页面。");
            location.reload(true);
        } 
        this.webController = webController;
        this.config = {
            callingNumer: {
                index: 0,
                number: ""
            },
        }
        this.init();
    }
    init() {
        getMessage("aiccyun_call", message => {
            switch (message.title) {
                case "call":
                    this.call(message.data);
                    break;
                case "hangUp":
                    this.hangUp();
                    break;
                case "changeCallNumber":
                    this.changeCallNumber(message.data);
                    break;
                default:
                    break;
            }
        });
    }
    async call(tel) {
        let targetInput = $("ul.phonebar li.phonebarstate").next().find("input.pho-input");
        targetInput.val(tel);
        dispatch(targetInput, "input");
        dispatch(targetInput, "change");
        syncSetTimeout(100);
        let callBtn = $(".pho-panel.panel1 .pho-bohao-sub2 li.callTo > a");
        dispatch(callBtn, "click");
    }
    hangUp() {
        let targetBtn = $("ul.phonebar > li.iconfont.icon-guaduan.allowed:nth-child(1)");
        if (targetBtn.length === 0) return;
        dispatch(targetBtn, "click");
    }
    async changeCallNumber(num) {
        if (num == this.config.callingNumer.index) {
            return;
        } else {
            let targetUl = $("ul.callingNumberList");
            let targetBtn = $("li.callSetting > div.setUp button.Determine");
            if (targetUl.length != 1 || targetBtn.length != 1) {
                console.error("collectionPlugin: \nError: aiccyun -> call.js -> changeCallNumber() -> targetUl.length != 1 || targetBtn.length != 1");
                return;
            };
            if (("" + num).length <= 2) {
                dispatch(targetUl.find("li").eq(num), "click");
            } else {
                dispatch(targetUl.find(`li:contains(${num})`)[0], "click")
            }
            $("#acwTimer").val(0);    // 设置整理时间0，如果不设置无法点击确定
            await syncSetTimeout(200);
            dispatch(targetBtn, "click");
            this.config.callingNumer.index = num;
        }
    }
}